package com.four.bmm.controller;

import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@WebServlet("/SmartUploadServlet")
public class SmartUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置上传文件保存路径
        String filePath = getServletContext().getRealPath("/") + "/image";
        System.out.println(filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        SmartUpload su = new SmartUpload();
        //初始化对象
        su.initialize(getServletConfig(), request, response);
        su.setCharset("UTF-8");
        //设置上传文件大小
        su.setMaxFileSize(1024 * 1024 * 10);
        //设置所有文件的大小
        su.setTotalMaxFileSize(1024 * 1024 * 100);
        //设置允许上传文件类型
        su.setAllowedFilesList("jpeg,jpg,gif");
        String result = "上传成功！";
        //设置禁止上传的文件类型
        try {
            su.setDeniedFilesList("rar,jsp,js");
            //上传文件
            su.upload();
            int count = su.save(filePath);
            System.out.println("上传成功" +  count + "个文件！");
        } catch (Exception e) {
            result = "上传失败！";
            e.printStackTrace();
        }
        String pic = su.getFiles().getFile(0).getFileName();
        System.out.println(pic+"-----");
        request.setAttribute("result", result);
        request.getRequestDispatcher("back/smartTest.jsp").forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
